from fastapi import Request, HTTPException, status
from fastapi.responses import JSONResponse
from app.utils.logger import logger
from datetime import datetime


class ExceptionMiddleware:
    """全局异常处理中间件"""
    
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
            
        async def custom_send(message):
            if message["type"] == "http.response.start":
                # 检查状态码是否表示错误
                status_code = message["status"]
                if status_code >= 400:
                    # 这里可以添加额外的错误处理逻辑
                    pass
            await send(message)

        try:
            await self.app(scope, receive, send)
        except HTTPException as exc:
            content = {
                "code": exc.status_code,
                "message": exc.detail,
                "data": None,
                "timestamp": datetime.utcnow().isoformat() + "Z"
            }
            response = JSONResponse(
                content=content,
                status_code=exc.status_code
            )
            await response(scope, receive, send)
        except Exception as exc:
            logger.error(f"Unhandled exception: {exc}", exc_info=True)
            content = {
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": "Internal server error",
                "data": None,
                "timestamp": datetime.utcnow().isoformat() + "Z"
            }
            response = JSONResponse(
                content=content,
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
            await response(scope, receive, send)